﻿var Post = require('../models/Post.js');

var _ = require('underscore');

//编辑
exports.edit = function (req, res) {
    if (req.session.user) {
        var _id = req.params.id;
        if (_id) {
            Post.findById(_id, function (err, news) {
                if (err) console.log(err);
                if (!news) res.redirect('./');
                else
                    res.render('admin/post/edit', {
                        title: '编辑',
                        id: news._id
            });
            });
        } else {
            res.render('admin/post/edit', {
                title: '编辑',
                id: ""
            });
        }
    } else {
        res.redirect('/login');
    }
}

//添加新闻 添加一条数据
exports.add = function (req, res) {
    var _news,
        _tags = req.body.tags.split(','),
        _id = req.body._id;
    console.log(_id);
    req.body.tags = _tags;
    req.body.user = req.session.user.name;
    if (!_id) {
        var d = new Post(req.body);
        d.save(function (err, news) {
            if (err) console.log(err);
            console.log(news);
            res.redirect('/news/'+ news._id);
        });
    } else {
        Post.findById(_id, function (err, news) {
            if (err) console.log(err);
            _news = _.extend(news, req.body);
            Post.findByIdAndUpdate(_id, _news, function (error, wnews) {
                if (error) console.log(error);
                console.log(news);
                res.redirect('/news/' + news._id);
            });
        });
    }
}
exports.detail = function (req, res) {
    var _id = req.params.id;
    console.log(_id);
        if (_id) {
            Post.findById(_id, function (err, news) {
                if (err) console.log(err);
                if (!news) res.redirect('/news');
                else
                    res.render('news', news);
            });
    } else {
            Post.fetch(function(err, ls) {
                res.render('list', ls);
            });
        }
}
exports.deletes = function (req, res) {
    var _id = req.params.id;
    Post.findById(_id, function (err, news) {
        if (err) console.log(err);
        if (news) news.remove();
        res.redirect('/news');
    })
}